package com.yidu.logisticssystem.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yidu.logisticssystem.entity.LogisticsCardriver;
import com.yidu.logisticssystem.entity.LogisticsStaff;
import com.yidu.logisticssystem.service.LogisticsStaffService;
import com.yidu.logisticssystem.utils.BaseMessage;
import com.yidu.logisticssystem.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.tools.Tool;
import java.io.File;
import java.io.IOException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 员工表(LogisticsStaff)表控制层
 *
 * @author makejava
 * @since 2021-03-08 16:46:56
 */
@RestController
@RequestMapping("logisticsStaff")
@Api(tags = "物流员工接口")
public class LogisticsStaffController {
    /**
     * 服务对象
     */
    @Resource
    private LogisticsStaffService logisticsStaffService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @PostMapping("selectOne/{id}")
    @ApiOperation("通过主键查询单条数据,返回唯一员工类")
    public BaseMessage selectOne(@PathVariable Integer id) {
        //new 一个BaseMessage
        BaseMessage bm=new BaseMessage();
        //判断id是否为空
        if (id==null){
            bm.setState(0);
            bm.setMessage("ID为空");
        }else {
            //不为空就根据ID查询，返回一个用户对象
            LogisticsStaff logisticsStaff=logisticsStaffService.queryById(id);
            bm.setState(1);
            bm.setMessage("找到啦");
            bm.setData(logisticsStaff);
        }
        return bm;
    }


    /**
     * 查询全部员工类，然后分页,返回一个集合
     * @param logisticsStaff
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("findAll")
    @ApiOperation("查询全部员工类，然后分页,返回一个集合")
    public Map<String,Object> findAll(LogisticsStaff logisticsStaff, Integer page, Integer limit){
        //将参数传入到分页助手类中
        PageHelper.startPage(page,limit);
        //new一个map
        Map<String,Object>map=new HashMap<>();
        //查询所有用户类
        List<LogisticsStaff>list=logisticsStaffService.queryAll(logisticsStaff);
        //查询到集合后，将集合数据封装到分页助手的pageinfo中
        PageInfo<LogisticsStaff> pageInfo=new PageInfo(list);
        //查询行数
        map.put("code",0);
        map.put("msg","");
        map.put("data",list);
        //传行数到前端页面 pageinfo.getTotal()
        map.put("count",pageInfo.getTotal());
        return map;
    }


    /**
     * 查询全部员工类，然后分页,返回一个集合
     * @param logisticsStaff
     * @return
     */
    @PostMapping("findAlls")
    @ApiOperation("查询全部员工类，然后分页,返回一个集合")
    public Map<String,Object> findAlls(LogisticsStaff logisticsStaff){
        //new一个map
        Map<String,Object>map=new HashMap<>();
        //查询所有用户类
        List<LogisticsStaff>list=logisticsStaffService.findAlls(logisticsStaff);
        //查询到集合后，将集合数据封装到分页助手的pageinfo中
        PageInfo<LogisticsStaff> pageInfo=new PageInfo(list);
        //查询行数
        map.put("code",0);
        map.put("msg",null);
        map.put("total",list.size());//显示数量
        map.put("rows",list);
        return map;
    }

    /**
     * 根据ID删除员工类
     * @param id
     * @return
     */
    @PostMapping("delete/{id}")
    @ApiOperation("根据ID删除员工类")
    public BaseMessage delete(@PathVariable Integer id){
        //定义一个布尔值 根据ID删除用户类，返回一个行数
        boolean flag=logisticsStaffService.deleteById(id);
        if (flag){
            return BaseMessage.succes();
        }else {
            return BaseMessage.fail();
        }
    }

    /**
     * 根据ID删除员工类
     * @param ids  //ids是字符串类型
     * @return
     */
    @PostMapping("deletes")
    @ApiOperation("根据ID删除员工类")
    public Map<String, Object> deletes(String ids){
        boolean flag=logisticsStaffService.deleteById(Integer.valueOf(ids));
        Map<String, Object> map = new HashMap<>();
        if (flag){
            map.put("msg","删除成功");
            return map;
        }else {
            map.put("msg","删除失败");
            return map;
        }
    }

    /**
     * 根据ID判断是增加还是修改，返回唯一行数
     * @param logisticsStaff
     * @return
     */
    @PostMapping("addOrUpdate")
    @ApiOperation("根据ID判断是增加还是修改，返回唯一行数")
    // 传入一个文件参数  @RequestParam(value = "staffPhoto_") MultipartFile file
    public Map<String,Object>addOrUpdate(@RequestParam(value = "staffPhoto_") MultipartFile file,LogisticsStaff logisticsStaff){
        //获取文件名 file.getOriginalFilename（）
        String fileName=file.getOriginalFilename();
        //判断 文件名是否空 “ ”
        if ("".equals(fileName)) {
        }else {
            //获取.的位置  fileName.lastIndexOf(".")
            int dian = fileName.lastIndexOf(".");
            //获取后缀名  fileName.substring(dian);
            String hz = fileName.substring(dian);
            //新文件名 UUID.randomUUID().toString()+后缀名
            String newFile = UUID.randomUUID().toString() + hz;
            //文件位置  File target = new File("D://4321//" + newFile);
            File target = new File("D://4321//" + newFile);
            try {
                file.transferTo(target);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //把新文件名添加到文件夹中 /imgs/+新文件名
            logisticsStaff.setStaffPhoto("/imgs/"+newFile);
        }
        //初始化 Map
        Map<String,Object>map=new HashMap<>();
        //判断员工ID是否为空
        if (logisticsStaff.getStaffId()==null){
            // 定义一个字符串 EN为随机生成员工编号 abcdefghijkqwertyupzxcvbnm1234567890
            final String EN="abcdefghijkqwertyupzxcvbnm1234567890";
            // new 一个新的随机数对象  random
            SecureRandom random= new SecureRandom();
            //定一个一个字符串为 “ ”;
            String num="";
            // for循环
            for (int i = 0; i < 3; i++) {
                //定一个一个字符类型的变量来接收 随机生成的编号  EN.charAt(random.nextInt(EN.length()))
                char c=EN.charAt(random.nextInt(EN.length()));
                // 在循环中把字符类型的变量+字符串
                num+=c;
            }
            //把字符串变量添加到数据库中
            logisticsStaff.setStaffNum(num);
            //把员工类添加到数据库中
            logisticsStaffService.insertSelective(logisticsStaff);
            map.put("state",1);
            map.put("msg","增加成功");
            if (logisticsStaff.getPostId()==3){
                LogisticsCardriver logisticsCardriver = new LogisticsCardriver();
                logisticsCardriver.setMapId(logisticsStaff.getMapId());
                logisticsCardriver.setStaffId(logisticsStaff.getZiId());
                logisticsStaffService.insertSelective2(logisticsCardriver);
            }
        }else {
            logisticsStaffService.updateByPrimaryKeySelective(logisticsStaff);
            map.put("state",1);
            map.put("msg","修改成功");
        }
        return map;
}
    /**
     * 根据职位ID查询管理人员信息
     * @return
     */
    @ApiOperation(value = "根据职位Id，查询管理人员信息")
    @PostMapping("selectCarOutPeople")
    public Map<String, Object> selectCarOutPeople() {
        //postId值 随管理职位id改变
        Integer postId = 1;
        //查询数据
        List<LogisticsStaff> list = logisticsStaffService.selectCarOutPeople(postId);
        return Tools.getLayUiMap(list);
    }


    /**
     * 根据地区id 查找快递员
     * @return
     */
    @ApiOperation(value = "根据地区id 查找快递员")
    @PostMapping("selectkdy")
    public Map<String, Object> selectkdy(HttpServletRequest request) {
        //查询数据
        List<LogisticsStaff> list = logisticsStaffService.selectkdy(request);
        return Tools.getLayUiMap(list);
    }


    /**
     * 根据职位ID查询司机信息
     * @return
     */
    @ApiOperation(value = "根据职位Id，查询司机信息")
    @PostMapping("selectDriver")
    public Map<String, Object> selectDriver() {
        //postId值 随司机职位id改变
        Integer postId = 3;
        //查询数据
        List<LogisticsStaff> list = logisticsStaffService.selectCarOutPeople(postId);
        return Tools.getLayUiMap(list);
    }


    /**
     * 员工登录方法，返回一个员工对象
     * @param logisticsStaff
     * @param request
     * @return
     */
    @ApiOperation("登录方法")
    @PostMapping("login")
    public BaseMessage login(LogisticsStaff logisticsStaff, HttpServletRequest request){
        //request.getSession().invalidate();//清空session
        BaseMessage bm=new BaseMessage();
        System.out.println("进员工登录方法了");
        LogisticsStaff logisticsStaff1=logisticsStaffService.login(logisticsStaff);
        if (logisticsStaff1!=null){
            HttpSession session=request.getSession();
            session.setAttribute("staff",logisticsStaff1);
            bm.setState(1);
        }else {
            bm.setState(0);
        }
        return bm;
    }

    /**
     * 查询全部方法
     * @return
     */
    @ApiOperation("查询全部方法")
    @PostMapping("selectAll")
    public BaseMessage findAll(){
        BaseMessage bm=new BaseMessage();
        List<LogisticsStaff>list=logisticsStaffService.findAll();
        bm.setData(list);
        return bm;
    }

    /**
     * 查询账号唯一
     * @param logisticsStaff
     * @return
     */
    @ApiOperation("查询唯一账号")
    @PostMapping("queryByStaffName")
    public BaseMessage queryByStaffName(LogisticsStaff logisticsStaff){
        LogisticsStaff logisticsStaff1=logisticsStaffService.queryByStaffName(logisticsStaff);
        if (logisticsStaff1==null){
            return BaseMessage.succes();
        }else {
            return BaseMessage.fail();
        }
    }


    /**
     * 根据ID批量删除员工类
     * @param ids //ids是字符串类型
     * @return
     */
    @ApiOperation("根据ID批量删除员工类,返回一个rows")
    @PostMapping("deleteAll")
    public BaseMessage deleteAll(String ids){
        BaseMessage bm=new BaseMessage();
        int rows=logisticsStaffService.deleteAll(ids);
        if (rows>0){
            bm.setState(1);
        }else {
            bm.setState(0);
        }
        return bm;
    }

    /**
     * 查询部门和职位
     * @param id
     * @return
     */
    @ApiOperation("查询部门和职位")
    @PostMapping("select/{id}")
    public BaseMessage select(@PathVariable Integer id){
        LogisticsStaff logisticsStaff1=logisticsStaffService.select(id);
        System.out.println(id);
        return BaseMessage.succes(logisticsStaff1);
    }


    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),
                true));
    }
}
